package com.example.demoyyy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demoyyy.JieKouService.AddressBookServiceJieKou;
import com.example.demoyyy.ShiTiYYY.AddressBook;
import com.example.demoyyy.common.BaseContext;
import com.example.demoyyy.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
     * 地址簿管理
     */
    @Slf4j
    @RestController
    @RequestMapping("/addressBook")
    public class AddressBookController {
        @Autowired
        private AddressBookServiceJieKou addressBookService;

        @PostMapping
        public R<String> add(@RequestBody AddressBook addressBook) {
            Long userId = BaseContext.getCurrentId();
            addressBook.setUserId(userId);
            addressBookService.save(addressBook);
            return R.success(1, "添加地址成功", null);
        }

        @GetMapping("/list")
        public R<List<AddressBook>> list() {
            Long userId = BaseContext.getCurrentId();
            LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AddressBook::getUserId, userId)
                    .orderByDesc(AddressBook::getIsDefault)
                    .orderByDesc(AddressBook::getUpdateTime);
            List<AddressBook> addressBooks = addressBookService.list(queryWrapper);
            return R.success(1, "查询地址成功", addressBooks);
        }

        @GetMapping("/default")
        public R<AddressBook> getDefault() {
            Long userId = BaseContext.getCurrentId();
            AddressBook defaultAddress = addressBookService.getDefaultByUserId(userId);
            return R.success(1, "查询默认地址成功", defaultAddress);
        }

        @PutMapping("/default")
        public R<String> setDefault(@RequestBody Map<String, Long> request) {
            Long id = request.get("id");
            Long userId = BaseContext.getCurrentId();
            addressBookService.setDefaultAddress(id, userId);
            return R.success(1, "默认地址设置成功", null);
        }

        @GetMapping("/{id}")
        public R<AddressBook> getById(@PathVariable Long id) {
            AddressBook addressBook = addressBookService.getById(id);
            return R.success(1, "根据id查询成功", addressBook);
        }

        @PutMapping
        public R<String> update(@RequestBody AddressBook addressBook) {
            addressBookService.updateById(addressBook);
            return R.success(1, "修改地址成功", null);
        }

        @DeleteMapping
        public R<String> delete(@RequestParam("ids") Long id) {
            addressBookService.removeById(id);
            return R.success(1, "删除地址成功", null);
        }
    }
